import {
  Component,
  OnInit,
  AfterViewInit,
  OnDestroy,
  Inject
} from "@angular/core";
import { LocaleService, TranslationService, Language } from "angular-l10n";
import Scrollbar from "smooth-scrollbar";
import { isPlatformBrowser, isPlatformServer } from "@angular/common";
import {
  ISelectSymbolResponse,
  IMu,
  IZi,
  IQuerySymbol
} from "@/trade/store/models/trade";
import * as fromTrade from "@/trade/store/reducers/index";
import * as fromMain from "@/main/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { Store, select } from "@ngrx/store";
import { TradeActions } from "@/trade/store/actions";
import { MainActions } from "@/main/store/actions";
import { map, filter } from "rxjs/operators";
import { Subscription } from "rxjs";
import { ActivatedRoute } from "@angular/router";
import { Router, NavigationEnd } from "@angular/router";
import { takeUntil, mergeMap } from "rxjs/operators";
import { forkJoin, combineLatest, ReplaySubject } from "rxjs";
import { FormControl } from "@angular/forms";

@Component({
  selector: "app-panel-market",
  templateUrl: "./panel-market.component.html",
  styleUrls: ["./panel-market.component.scss"]
})
export class PanelMarketComponent implements OnInit, AfterViewInit, OnDestroy {
  @Language() lang: string;

  onMu: IMu = {
    symbol: "",
    lists: []
  };

  onMu$: FormControl = new FormControl({
    symbol: "",
    lists: []
  });

  search$: FormControl = new FormControl("");

  ziLists: Array<IZi> = [];
  ziLists$: ReplaySubject<Array<IZi>> = new ReplaySubject<any[]>(1);
  muLists: Array<IMu> = [];

  trade$ = this.store.pipe(select("trade"));

  symbolLists$ = this.store
    .pipe(select(fromRoot.symbolLists))
    .pipe(filter(symbolLists => !!symbolLists));

  querySymbol: IQuerySymbol;

  sub$ = {
    symbolListsSub$: null,
    searchSub$: null,
    searchAndOnMuSub$: null,
    onMuSub$: null
  };

  search = "";

  constructor(
    private store: Store<fromTrade.State | fromMain.State | fromRoot.State>,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    @Inject("UtilsService") private utilsService
  ) {}

  ngAfterViewInit() {}

  ngOnInit() {
    this.store.dispatch(
      new TradeActions.SelectSymbol({
        req: undefined
      })
    );
    this.addListen();
  }

  addListen() {
    this.sub$.symbolListsSub$ = this.symbolLists$.subscribe(symbolLists => {
      this.muLists = symbolLists;
      this.setOnMu({
        symbol: "BTC",
        lists: []
      });
    });

    this.sub$.searchAndOnMuSub$ = combineLatest(
      this.search$.valueChanges,
      this.ziLists$
    ).subscribe(([search, ziLists]) => {});

    this.sub$.onMuSub$ = this.onMu$.valueChanges.subscribe(e => {
      const timer = setTimeout(() => {
        this.ziLists$.next(
          this.ziLists.slice().filter(d => {
            return d.symbol.indexOf(this.search.toUpperCase()) >= 0;
          })
        );
        clearTimeout(timer);
      }, 0);
    });

    this.sub$.searchSub$ = this.search$.valueChanges.subscribe(e => {
      this.search = e;
      this.ziLists$.next(
        this.ziLists.slice().filter(d => {
          return d.symbol.indexOf(e.toUpperCase()) >= 0;
        })
      );
    });
  }

  onInputSearch(e) {
    const val = e.target.value;
    // this.search = val;
    // this.ziLists$.next(
    //   this.ziLists.slice().filter(d => {
    //     return d.symbol.indexOf(val.toUpperCase()) >= 0;
    //   })
    // );
  }
  /**
   * 跳转到指定子币
   *
   * @param {IZi} zi
   * @memberof PanelSymbolComponent
   */
  toOnZi(item: any) {
    this.router.navigate(["/trade/home"], {
      queryParams: { symbol: `${item.symbol}_${this.onMu.symbol}` }
    });
  }

  setOnMu(mu: IMu) {
    const muItem = this.getMuItem(mu);
    if (!!muItem) {
      this.onMu = muItem;
      this.onMu$.setValue(this.onMu);

      this.ziLists = this.getZiLists(mu);
      this.ziLists$.next(this.ziLists.slice());
    }
  }

  getMuItem(mu: IMu): IMu {
    const muLists = this.muLists.slice();
    for (const key in muLists) {
      if (muLists.hasOwnProperty(key)) {
        const item = this.muLists[key];
        if (item.symbol === mu.symbol) {
          return item;
        }
      }
    }
    return undefined;
  }

  /**
   * 获取母币的子币列表
   *
   * @param {IMu} mu
   * @returns {Array<IZi>}
   * @memberof PanelSymbolComponent
   */
  getZiLists(mu: IMu): Array<IZi> {
    const muLists = this.muLists.slice();
    for (const key in muLists) {
      if (muLists.hasOwnProperty(key)) {
        const item = muLists[key];
        if (item.symbol === mu.symbol) {
          return item.lists;
        }
      }
    }
    return [];
  }

  ngOnDestroy() {
    this.utilsService.unsub(this.sub$);
  }
}
